#include <stdio.h>
#include <sys/types.h>			/* See NOTES */
#include <sys/socket.h>
#include <netinet/in.h>
#include <netinet/ip.h>			/* superset of previous */
#include <errno.h>
#include <arpa/inet.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#define N 64

int main(int argc, const char *argv[])
{
	int server_fd;
	int client_fd;
	int ret;
	char buf[N] = "";
	struct sockaddr_in server_addr;
	struct sockaddr_in client_addr;
	socklen_t addrlen = sizeof(client_addr);
	server_fd = socket(AF_INET, SOCK_STREAM, 0);
	if(server_fd == -1)
	{
		perror("fail to socket");
		return -1;
	}
	memset(&server_addr,0,sizeof(server_addr));
	server_addr.sin_family = AF_INET;
	server_addr.sin_port = htons(atoi(argv[2]));
	server_addr.sin_addr.s_addr = inet_addr(argv[1]);

	ret = bind(server_fd,(struct sockaddr *)&server_addr,sizeof(server_addr));
	if(ret == -1)
	{
		perror("fail to bind");
		return -1;
	}
	printf("Bind success\n");

	ret = listen(server_fd, 5);
	if(ret == -1)
	{
		perror("fail to listen");
		return -1;
	}
	printf("Listen success\n");

	client_fd = accept(server_fd, (struct sockaddr *)&client_addr, &addrlen);
	if(client_fd == -1)
	{
		perror("fail to accpet");
		return -1;
	}
	printf("client ip:%s\n",inet_ntoa(client_addr.sin_addr));

	while(1)
	{
		ret = recv(client_fd, buf, N, 0);
		if(ret > 0)
		{
			printf("%s\n",buf);
			memset(buf,0,64);
		}
		else if(ret < 0)
		{
			perror("fail to recv");
			close(client_fd);
			close(server_fd);
			return -1;
		}
		else
		{
			printf("perr exit\n");
			close(client_fd);
			close(server_fd);
			return 0;
		}
	}

	return 0;
}
